package com.example.demo.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.common.BaseResult;
import com.example.demo.mapper.UserMapper;

@RestController
public class LoginController {

	@Autowired
	private UserMapper userMapper;

	/**
	 * 登陆
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@GetMapping(value = "/login")
	public BaseResult login(String username, String password) {
		// 从SecurityUtils里边创建一个 subject
		Subject subject = SecurityUtils.getSubject();
		// 在认证提交前准备 token（令牌）
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		// 执行认证登陆
		subject.login(token);
		// 根据权限，指定返回数据
		String role = userMapper.getRole(username);
		if ("user".equals(role)) {
			return new BaseResult(200, "用户登陆成功", token);
		}
		if ("admin".equals(role)) {
			return new BaseResult(200, "管理员登陆成功", token);
		}
		return new BaseResult(200, "权限有问题", null);
	}

	/**
	 * 注销
	 * 
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public BaseResult logout() {
		Subject subject = SecurityUtils.getSubject();
		// 注销
		subject.logout();
		return new BaseResult(200, "注销完成", null);
	}

	/**
	 * shrio的两个提示url
	 * 
	 * @return
	 */
	@GetMapping(value = "/notLogin")
	public BaseResult notLogin() {
		return new BaseResult(200, "没有登陆", null);
	}

	@GetMapping(value = "/notRole")
	public BaseResult notRole() {
		return new BaseResult(200, "没有权限", null);
	}
}
